<script setup lang="ts">
import {
  inventoryTimeList,
  LibraryOptions,
  inventoryTypeOptions,
  addinventoryTime,
  delinventoryTime,
  updateinventoryTime,
  ForminventoryTime,
} from "@/api/time/index";
import type {
  RequestParams,
  inventoryTimeRequestParams,
} from "@/api/time/type";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
const RobotList = ref([] as any); //列表数据
const libraryaOpt = ref([] as any);
const inventoryOptions = ref([] as any);

// const libOptions = async () => {
//   const res = await inventoryTypeOptions();
//   inventoryOptions.value = res.data;
//   console.log(res.data, "inventoryTypeOptions");
// };

const queryFormRef = ref(); //refForm
const ids = ref([]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
const ruleFormRef = ref(); //弹框表单
const ruleForm = ref({} as any);
const rowId = ref();
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
} as RequestParams);
const rules = reactive({
  libraryId: [{ required: true, message: "请选择图书馆 ", trigger: "change" }],
  typeId: [{ required: true, message: "请选择盘点类型", trigger: "blur" }],
  timeName: [
    { required: true, message: "时间名称不能为空", trigger: "blur" },
    { min: 1, max: 50, message: "时间名称过长", trigger: "blur" },
  ],
  startTime: [
    { required: true, message: "请选择开始时间 ", trigger: "change" },
  ],
});
/**
 * 列表数据
 */
const getRbtList = async () => {
  try {
    const res = await inventoryTimeList(queryParams.value);
    RobotList.value = res.data.records;
    total.value = res.data.total;
    // console.log(res.data, "分页列表");
    // console.log(queryParams.value);
  } catch (error) {
    // console.error(error);
  }
};
/**
 * 重置
 */
// const resetQuery = () => {
//   queryFormRef.value.resetFields();
//   queryParams.value = {} as RequestParams;
//   queryParams.value.pageNum = 1;
//   queryParams.value.pageSize = 10;
//   getRbtList();
// };
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */

const openDialog = async () => {
  title.value = "新增";
  dialogVisible.value = true;

  const res = await LibraryOptions(useStore.encryptedData);
  libraryaOpt.value = res.data;
  //console.log(res.data, "LibraryOptions");
  const ress = await inventoryTypeOptions(useStore.encryptedData);
  inventoryOptions.value = ress.data;
  //console.log(ress.data, "inventoryTypeOptions");
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  try {
    // 表示当前页面正在异步处理中
    loading.value = true;
    // 验证表单数据是否合法
    const isValid = await ruleFormRef.value.validate();
    if (isValid) {
      //   console.log(ruleForm.value, "杀杀杀撒海");
      // 提交数据到服务器
      if (title.value === "新增") {
        const res = await addinventoryTime(ruleForm.value);
        if (res.code === 200) {
          ElMessage.success("新增成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      } else {
        const res = await updateinventoryTime(ruleForm.value);
        if (res.code === 200) {
          ElMessage.success("修改成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      }
    }
  } catch (error) {
    console.error(error);
    // 在发生异常时，取消页面加载状态
    loading.value = false;
  }
};
/**
 * 编辑
 */
const edit = async (row: any) => {
  title.value = "编辑";
  rowId.value = row.id;

  const res = await LibraryOptions(useStore.encryptedData);
  libraryaOpt.value = res.data;
  //console.log(res.data, "LibraryOptions");
  const ress = await inventoryTypeOptions(useStore.encryptedData);
  inventoryOptions.value = ress.data;
  const { data } = await ForminventoryTime(row.id);
  ruleForm.value = data;
  dialogVisible.value = true;
};
/**
 * 删除
 */
const dell = (row: any) => {
  const userIds = [row.id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async function () {
    const res = await delinventoryTime(row.id);
    if (res.code == 200) {
      getRbtList();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
  });
};
/**
 * 枚举
 */
// const taskStatusOptions = [
//   { id: 0, name: "只执行一次" },
//   { id: 1, name: "每天执行一次" },
//   { id: 2, name: "每周执行一次" },
//   { id: 3, name: "每月一次" },
//   { id: 4, name: "季度一次" },
//   { id: 5, name: "半年一次" },
//   { id: 6, name: "一年一次" },
// ];
// const getRobotStatus = (status: number) => {
//   const STATUSES = [
//     { id: 0, name: "只执行一次" },
//     { id: 1, name: "每天执行一次" },
//     { id: 2, name: "每周执行一次" },
//     { id: 3, name: "每月一次" },
//     { id: 4, name: "季度一次" },
//     { id: 5, name: "半年一次" },
//     { id: 6, name: "一年一次" },
//   ];
//   const matched = STATUSES.find((item) => item.id === status);
//   return matched ? matched.name : "";
// };
const formatDateTime = () => {
  const formattedDateTime = dayjs(ruleForm.value.startTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  ruleForm.value.startTime = formattedDateTime;
};
onMounted(() => {
  getRbtList();
  // libOptions();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRbtList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRbtList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
</script>

<template>
  <div class="app-container">
    <!-- <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="时间名称">
          <el-input
            v-model="queryParams.timeName"
            placeholder="请输入时间名称"
          />
        </el-form-item>
        <el-form-item label="执行方式">
          <el-select
            v-model="queryParams.executeType"
            placeholder="请选择执行方式"
          >
            <el-option
              v-for="(status, index) in taskStatusOptions"
              :key="index"
              :label="status.name"
              :value="status.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRbtList">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <el-card>
      <template #header>
        <el-button type="success" @click="openDialog">新增</el-button>
        <!-- <el-button type="danger" :disabled="ids.length === 0" @click="dell"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="RobotList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" :align="'center'" /> -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column label="时间名称" prop="timeName" :align="'center'" />
        <!-- <el-table-column
          label="执行方式 "
          prop="executeType"
          :align="'center'"
          width="130"
        >
          <template #default="{ row }">
            {{ getRobotStatus(row.executeType) }}
          </template>
        </el-table-column> -->
        <el-table-column label="开始时间" prop="startTime" :align="'center'" />
        <!-- <el-table-column label="创建时间" prop="createTime" :align="'center'" />
        <el-table-column label="更新时间" prop="updateTime" :align="'center'" /> -->

        <el-table-column
          fixed="right"
          label="操作"
          :align="'center'"
          width="220"
        >
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="edit(row)"
              >编辑</el-button
            >
            <el-button type="primary" link size="small" @click="dell(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item
          label="开始时间"
          prop="startTime"
          style="white-space: nowrap; width: 100%"
        >
          <el-date-picker
            v-model="ruleForm.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间"
            @change="formatDateTime"
          />
        </el-form-item>
        <el-form-item label="图书馆" prop="libraryId">
          <el-select v-model="ruleForm.libraryId" placeholder="请选择图书馆">
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="盘点类型" prop="typeId">
          <el-select v-model="ruleForm.typeId" placeholder="请选择盘点类型">
            <el-option
              v-for="item in inventoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="时间名称"
          prop="timeName"
          style="white-space: nowrap"
        >
          <el-input
            v-model="ruleForm.timeName"
            placeholder="请输入盘点时间名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}
</style>
